import MenuAPI from "@/api/system/menu-api";
import RoleAPI from "@/api/system/role-api";
import { getMenuTree } from "@/commonData";

export const useAuth = () => {
  const isExpanded = ref(true);
  const permKeywords = ref("");
  const permTreeRef = ref();
  const checkedRole: any = ref({});
  const menuTree: any = ref([]);

  const handlePermFilter = (
    value: string,
    data: {
      [key: string]: any;
    }
  ) => {
    if (!value) return true;
    return data.label.includes(value);
  };

  // 展开/收缩 菜单权限树
  const togglePermTree = () => {
    isExpanded.value = !isExpanded.value;
    if (permTreeRef.value) {
      Object.values(permTreeRef.value.store.nodesMap).forEach((node: any) => {
        if (isExpanded.value) {
          node.expand();
        } else {
          node.collapse();
        }
      });
    }
  };

  const setRoleMenu = (roleId: string) => {
    // 回显角色已拥有的菜单
    RoleAPI.getRoleMenuIds(roleId).then((data) => {
      const checkedMenuIds = data;
      checkedMenuIds.forEach((menuId) => permTreeRef.value!.setChecked(menuId, true, false));
    });
  };

  // 打开分配菜单权限弹窗
  const getMenuTreeAndRoleMenu = async (row?: any) => {
    const roleId = row?.id;
    // // 获取所有的菜单
    menuTree.value = await MenuAPI.getOptions();
    if (roleId) {
      // checkedRole.value.id = roleId;
      // checkedRole.value.name = row.name;
      // 回显角色已拥有的菜单
      setRoleMenu(roleId);
    }
  };

  // 分配菜单权限提交
  const handleAssignPermSubmit = async () => {
    const roleId = checkedRole.value.id || 2; // 默认角色id弄个2
    if (roleId) {
      const checkedMenuIds: number[] = permTreeRef
        .value!.getCheckedNodes(false, true)
        .map((node: any) => node.value);

      await RoleAPI.updateRoleMenus(roleId, checkedMenuIds);
      ElMessage.success("分配权限成功");

      //   RoleAPI.updateRoleMenus(roleId, checkedMenuIds)
      //     .then(() => {
      //       ElMessage.success("分配权限成功");
      //       // assignPermDialogVisible.value = false;
      //       // handleResetQuery();
      //     })
      //     .finally(() => {});
      // }
    }
  };

  // 权限筛选
  watch(permKeywords, (val) => {
    permTreeRef.value!.filter(val);
  });
  return {
    isExpanded,
    permKeywords,
    checkedRole,
    permTreeRef,
    getMenuTreeAndRoleMenu,
    menuTree,

    setRoleMenu,
    handlePermFilter,
    togglePermTree,
    handleAssignPermSubmit,
  };
};
